﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LoginForm
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            timer1.Start();
            groupBox3.Text = DateTime.Now.ToString("D");            
            getUsername();            
        }
        private string today = DateTime.Now.DayOfWeek.ToString();
        private static bool flag = false;
        private void getUsername() {
            User u = SunnyIO.ReadNoteAccount();
            if (u != null)
            {
                toolStripUsername.Text = "Hi, " + u.Username + " !";
            }
            else {
                toolStripUsername.Text = "Unknown";
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Do you want to exit ?","Exit Dialog",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }            
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Do you want to logout ?", "Logout Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                this.Hide();
                Form1 f = new Form1();
                f.Show(); 
            }                                    
        }
        
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dateTime = DateTime.Now;
            this.lblTime.Text = dateTime.ToString();
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            string chooseday = monthCalendar1.SelectionStart.DayOfWeek.ToString();            
            groupBox3.Text = monthCalendar1.SelectionStart.ToLongDateString();
            List<Schedule> schedules = SunnyIO.GetScheduleFromXML(FileName.schedule, chooseday);
            fillTableTimeManager(schedules);
            
        }

        private void fillTableTimeManager(List<Schedule> schedules) {
            DataTable table = new DataTable();
            table.Columns.Add("STT");
            table.Columns.Add("Thời Gian");
            table.Columns.Add("Học Sinh");
            table.Columns.Add("Lớp");
            table.Columns.Add("Địa Điểm");            
            if (schedules != null)
            {
                foreach (Schedule s in schedules)
                {
                    DataRow row = table.NewRow();
                    row[0] = s.No;
                    row[1] = s.Time;
                    row[2] = s.Student;
                    row[3] = s.Education;
                    row[4] = s.Address;
                    table.Rows.Add(row);
                }
            }            
            dataGridView1.DataSource = table;
            dataGridView1.Columns[0].Width = 40;
            dataGridView1.Columns[1].Width = 150;
            dataGridView1.Columns[2].Width = 300;
            dataGridView1.Columns[3].Width = 70;
            dataGridView1.Columns[4].Width = 500;
        }

        private void Main_Load(object sender, EventArgs e)
        {            
            List<Schedule> schedules = SunnyIO.GetScheduleFromXML(FileName.schedule, today);
            fillTableTimeManager(schedules);
            tabControl1.TabPages.Add(new MyTabPage(new NotePage()));
        }
              

        private void toolStripRefresh_Click(object sender, EventArgs e)
        {
            List<Schedule> schedules = SunnyIO.GetScheduleFromXML(FileName.schedule, today);
            fillTableTimeManager(schedules);
            tabControl1.TabPages.Clear();
            tabControl1.TabPages.Add(new MyTabPage(new NotePage()));
        }

        private void toolStripSave_Click(object sender, EventArgs e)
        {
            TabPage myTab = new MyTabPage(new NotePage());
            if (!IsSameTabpageName(myTab))
            {
                tabControl1.TabPages.Add(myTab);
                tabControl1.SelectedTab = myTab;
            }
            
        }
        private List<Schedule> CreateNewShedule() {
            List<Schedule> list = new List<Schedule>();
            int rows = dataGridView1.Rows.Count;
            string no, time, student, education, address;
            for (int i = 0; i < rows-1; i++)
            {
                DataGridViewRow row = dataGridView1.Rows[i];
                if (!Validation.IsEmpty(row.Cells[0].Value.ToString()))
                {
                    no = row.Cells[0].Value.ToString();
                }
                else {
                    no = (i + 1).ToString();
                }
                if (!Validation.IsEmpty(row.Cells[1].Value.ToString()))
                {
                    time = row.Cells[1].Value.ToString();
                }
                else {
                    time = "watting...";
                }
                if (!Validation.IsEmpty(row.Cells[2].Value.ToString()))
                {
                     student = row.Cells[2].Value.ToString();
                }
                else {
                     student = "";
                }
                if (!Validation.IsEmpty(row.Cells[3].Value.ToString()))
                {
                     education = row.Cells[3].Value.ToString();
                }
                else {
                    education = "";
                }
                if (!Validation.IsEmpty(row.Cells[4].Value.ToString()))
                {
                    address = row.Cells[4].Value.ToString();
                }
                else {
                    address = "";
                }
                Schedule s = new Schedule()
                {
                    No = no,
                    Time = time,
                    Student = student,
                    Education = education,
                    Address = address
                };
                list.Add(s);
            }
            return list;
        }
        
        //event tao contextmenustrip save khi chuot fai tai dataGrid
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) {
                ContextMenuStrip menuStrip = new ContextMenuStrip();
                menuStrip.Items.Add("Save");
                dataGridView1.ContextMenuStrip = menuStrip;
                menuStrip.ItemClicked += new ToolStripItemClickedEventHandler(toolStrip_Click);                
            }            
        }
        private void toolStrip_Click(object sender, EventArgs e) {
            DialogResult result = MessageBox.Show("Em Có Muốn Lưu Thay Đổi Không?", "Save Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                if (dataGridView1.RowCount > 1)
                {
                    List<Schedule> list = CreateNewShedule();
                    string date = monthCalendar1.SelectionStart.DayOfWeek.ToString();
                    if (SunnyIO.InsertSchedule(FileName.schedule, list, date))
                    {
                        MessageBox.Show("Lưu Thành Công", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        MessageBox.Show("Lưu Thất Bại", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        //event calendar
        private void pictureBox1_Click(object sender, EventArgs e)
        {            
            if (!flag)
            {
                flag = !flag;
                monthCalendar1.Hide();
                webBrowserClock.Show();
            }
            else {
                flag = !flag;
                monthCalendar1.Show();
                webBrowserClock.Hide();
            }
        }

        // event dong tabpages
        private ContextMenuStrip getCMSForTabControl() {
            ContextMenuStrip cms = new ContextMenuStrip();
            cms.Items.Add("Close",null,new EventHandler(Item_Clicked));            
            return cms;
        }
        private void Item_Clicked(object sender, EventArgs e) {
            TabPage current_tab = tabControl1.SelectedTab;
            tabControl1.TabPages.Remove(current_tab);
        }

        private void tabControl1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                tabControl1.ContextMenuStrip = getCMSForTabControl();
            }
            if (e.Button == MouseButtons.Left && e.Clicks == 2)
            {
                if (!flag)
                {
                    flag = !flag;
                    groupBox3.Hide();
                }
                else
                {
                    flag = !flag;
                    groupBox3.Show();
                }
            }
        }

        private void tabControl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                TabPage current_tab = tabControl1.SelectedTab;
                tabControl1.TabPages.Remove(current_tab);
            }
        }

        private bool IsSameTabpageName(TabPage myTabpage) {
            foreach (TabPage tab in tabControl1.TabPages)
            {
                if (tab.Text.Contains(myTabpage.Text)) {
                    return true;
                }
            }
            return false;
        }

        private void thờiKhóaBiểuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TabPage myTab = new MyTabPage(new TimePage());
            if (!IsSameTabpageName(myTab))
            {
                tabControl1.TabPages.Add(myTab);
                tabControl1.SelectedTab = myTab;
            }
            
        }

        private void sửaLịchDạyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("OK");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<Pupil> list = SunnyIO.GetAllPupils(FileName.pupil);
            MessageBox.Show(""+list.Count);
        }

        private void danhSáchHọcSinhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TabPage myTab = new MyTabPage(new Student());
            if (!IsSameTabpageName(myTab)) {
                tabControl1.TabPages.Add(myTab);
                tabControl1.SelectedTab = myTab;
            }
        }


    }
}
